using ERPBackend.Data;
using ERPBackend.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ERPBackend.Services
{
    public class SalesOrderService : ISalesOrderService
    {
        private readonly ApplicationDbContext _context;

        public SalesOrderService(ApplicationDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public async Task<List<SalesOrder>> GetAllSalesOrdersAsync()
        {
            return await _context.SalesOrders
                .Include(so => so.SalesOrderItems)
                .Include(so => so.Customer)
                .ToListAsync();
        }

        public async Task<SalesOrder> GetSalesOrderByIdAsync(int id)
        {
            return await _context.SalesOrders
                .Include(so => so.SalesOrderItems)
                .Include(so => so.Customer)
                .FirstOrDefaultAsync(so => so.Id == id);
        }

        public async Task<SalesOrder> CreateSalesOrderAsync(SalesOrder salesOrder)
        {
            // 确保订单编码唯一
            if (await _context.SalesOrders.AnyAsync(so => so.OrderCode == salesOrder.OrderCode))
            {
                throw new Exception("订单编码已存在");
            }

            // 设置默认状态为待审核
            if (salesOrder.Status != 0)
            {
                salesOrder.Status = 0;
            }

            // 计算订单总金额和未收款金额
            if (salesOrder.SalesOrderItems != null && salesOrder.SalesOrderItems.Any())
            {
                salesOrder.TotalAmount = salesOrder.SalesOrderItems.Sum(soi => soi.TotalAmount);
                salesOrder.UnpaidAmount = salesOrder.TotalAmount;
                salesOrder.ReceivedAmount = 0;

                // 设置行号
                for (int i = 0; i < salesOrder.SalesOrderItems.Count; i++)
                {
                    salesOrder.SalesOrderItems[i].LineNumber = i + 1;
                }
            }

            _context.SalesOrders.Add(salesOrder);
            await _context.SaveChangesAsync();

            return salesOrder;
        }

        public async Task<bool> UpdateSalesOrderAsync(SalesOrder salesOrder)
        {
            var existingOrder = await _context.SalesOrders
                .Include(so => so.SalesOrderItems)
                .FirstOrDefaultAsync(so => so.Id == salesOrder.Id);

            if (existingOrder == null)
            {
                return false;
            }

            // 检查订单状态，如果已审核或已关闭则不允许修改
            if (existingOrder.Status == 1 || existingOrder.Status == 2)
            {
                throw new Exception("已审核或已关闭的订单不能修改");
            }

            // 检查订单编码是否已被其他订单使用
            if (existingOrder.OrderCode != salesOrder.OrderCode &&
                await _context.SalesOrders.AnyAsync(so => so.OrderCode == salesOrder.OrderCode))
            {
                throw new Exception("订单编码已存在");
            }

            // 更新订单信息
            _context.Entry(existingOrder).CurrentValues.SetValues(salesOrder);

            // 处理订单明细
            // 删除已移除的明细
            var existingItems = existingOrder.SalesOrderItems.ToList();
            foreach (var existingItem in existingItems)
            {
                if (!salesOrder.SalesOrderItems.Any(soi => soi.Id == existingItem.Id))
                {
                    _context.SalesOrderItems.Remove(existingItem);
                }
            }

            // 添加或更新明细
            foreach (var item in salesOrder.SalesOrderItems)
            {
                if (item.Id == 0)
                {
                    // 新明细
                    item.SalesOrderId = salesOrder.Id;
                    _context.SalesOrderItems.Add(item);
                }
                else
                {
                    // 更新现有明细
                    var existingItem = existingItems.FirstOrDefault(soi => soi.Id == item.Id);
                    if (existingItem != null)
                    {
                        _context.Entry(existingItem).CurrentValues.SetValues(item);
                    }
                }
            }

            // 重新计算订单总金额
            existingOrder.TotalAmount = existingOrder.SalesOrderItems.Sum(soi => soi.TotalAmount);
            existingOrder.UnpaidAmount = existingOrder.TotalAmount - existingOrder.ReceivedAmount;

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> ApproveSalesOrderAsync(int id, int approvedBy)
        {
            var order = await _context.SalesOrders.FindAsync(id);
            if (order == null)
            {
                return false;
            }

            // 检查订单状态，如果不是待审核则不允许审核
            if (order.Status != 0)
            {
                throw new Exception("只有待审核的订单才能审核");
            }

            // 更新订单状态
            order.Status = 1;
            order.ApprovedBy = approvedBy;
            order.ApprovedTime = DateTime.Now;

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> CloseSalesOrderAsync(int id, int closedBy, string reason)
        {
            var order = await _context.SalesOrders.FindAsync(id);
            if (order == null)
            {
                return false;
            }

            // 检查订单状态，如果不是已审核则不允许关闭
            if (order.Status != 1)
            {
                throw new Exception("只有已审核的订单才能关闭");
            }

            // 更新订单状态
            order.Status = 2;
            order.CloseReason = reason;
            order.ClosedBy = closedBy;
            order.ClosedTime = DateTime.Now;

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<bool> DeleteSalesOrderAsync(int id)
        {
            var order = await _context.SalesOrders
                .Include(so => so.SalesOrderItems)
                .FirstOrDefaultAsync(so => so.Id == id);

            if (order == null)
            {
                return false;
            }

            // 检查订单状态，如果已审核则不允许删除
            if (order.Status == 1)
            {
                throw new Exception("已审核的订单不能删除");
            }

            // 删除订单明细
            _context.SalesOrderItems.RemoveRange(order.SalesOrderItems);

            // 删除订单
            _context.SalesOrders.Remove(order);

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<List<SalesOrder>> SearchSalesOrdersAsync(string keyword = null, int? customerId = null, int? status = null)
        {
            var query = _context.SalesOrders
                .Include(so => so.Customer)
                .AsQueryable();

            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(so => so.OrderCode.Contains(keyword) || so.OrderName.Contains(keyword));
            }

            if (customerId.HasValue)
            {
                query = query.Where(so => so.CustomerId == customerId.Value);
            }

            if (status.HasValue)
            {
                query = query.Where(so => so.Status == status.Value);
            }

            return await query.ToListAsync();
        }
    }
}